package bm.com.framework.redis.unit;

import bm.com.framework.common.config.EnumCode;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUnits {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 开始时间戳,此处的时间戳为预生成
     */
    private static final long BEGIN_TIMESTAMP = 1713974400L;

    /**
     *
     */
    private static final int COUNT_BITS = 18;

    /**
     * 默认有效期
     */
    private static final int DEFAULT_EXPIRED_TIME = EnumCode.TIME_86400;


    /**
     * 设置有效期
     */
    public boolean setExpired(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().getAndExpire(key, time,TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception E) {
//            log.error("RedisUtils.set fail,message:{}", E.getMessage());
            E.printStackTrace();
            return false;
        }
    }

    /**
     * 设置字符串，并设置有效期
     */
    public void set(String key, String value, long time) {
        try {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } catch (Exception E) {
//            log.error("RedisUtils.set fail,message:{}", E.getMessage());
            E.printStackTrace();
        }
    }

    /**
     * 获取字符串信息
     * @param key
     * @return
     */
    public String get(String key){
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除制定的key
     * @param key
     * @return
     */
    public String del(String key){
        return (String)redisTemplate.opsForValue().getAndDelete(key);
    }

}
